package com.bumptech.glide.load.engine;

import com.bumptech.glide.util.LogUtil;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;

/** A class that can safely recycle recursive resources. */
class ResourceRecycler {
  static final int RECYCLE_RESOURCE = 1;
  private boolean isRecycling;
  private final EventHandler handler =createMainThreadHandler();

  synchronized void recycle(Resource<?> resource, boolean forceNextFrame) {
    if (isRecycling || forceNextFrame) {
      // If a resource has sub-resources, releasing a sub resource can cause it's parent to be
      // synchronously evicted which leads to a recycle loop when the parent releases it's children.
      // Posting breaks this loop.
      handler.sendEvent(InnerEvent.get(ResourceRecycler.RECYCLE_RESOURCE, resource));
      
    } else {
      isRecycling = true;
      resource.recycle();
      isRecycling = false;
    }
  }


  private static EventHandler createMainThreadHandler() {
        EventHandler eventHandler = new EventHandler(EventRunner.getMainEventRunner()) {
            @Override
            public void processEvent(InnerEvent event) {

                int eventId = event.eventId;
                switch (eventId) {
                    case RECYCLE_RESOURCE: {
                        Resource<?> resource = (Resource<?>) event.object;
                        resource.recycle();
                        break;
                    }

                    default:
                        break;
                }
            }
        };
        return eventHandler;
    }
    
}
